package com.woniuxy.microsystemsarserver.controller;

import com.github.pagehelper.PageInfo;
import com.slsupermarket.common.res.ResponseMsg;
import com.woniuxy.microsystemsarserver.bean.PageRequestBean;
import com.woniuxy.microsystemsarserver.bean.StoreBean;
import com.woniuxy.microsystemsarserver.service.IServiceOrderService;
import com.woniuxy.microsystemsarserver.service.IStoreService;
import com.woniuxy.microsystemsarserver.util.ExcelUtil;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.util.List;

/**
 * 门店管理
 * @author 杨灿
 */
@RestController
@RequestMapping("/store")
public class StoreController {
    @Resource
    private IStoreService storeService;

    @Resource
    private IServiceOrderService serviceOrderService;
    /**
     * 分页查询门店信息
     * @param storeBean
     * @param currentPage
     * @param userId
     * @return
     */
    @RequestMapping("/allByPage")
    public ResponseMsg findByPage(StoreBean storeBean,Integer currentPage,Long userId){
        PageRequestBean pageRequestBean = new PageRequestBean();
        pageRequestBean.setPageNum(currentPage);
        pageRequestBean.setLimit(5);
        PageInfo<StoreBean> byPage = storeService.findByPage(storeBean, pageRequestBean, userId);
        return new ResponseMsg().builder().code(200).data(byPage).msg("查询成功").build();
    }

    /**
     * 添加门店信息
     * @param storeBean
     * @param userId
     * @return
     */
    @RequestMapping("/add")
    public ResponseMsg saveStore(StoreBean storeBean,Long userId){
        //如果当前用户购买的开通门店业务小于或等于用户拥有门店数，提示需要先购买门店服务
        if (serviceOrderService.countByUserId(userId)<=serviceOrderService.countByUserId(userId)){
            return new ResponseMsg().builder().code(203).msg("请先购买门店服务").build();
        }else {
            int row = storeService.saveStore(storeBean, userId);
            if (row > 0) {
                return new ResponseMsg().builder().code(200).msg("添加成功").build();
            } else {
                return new ResponseMsg().builder().code(201).msg("添加失败").build();
            }
        }

    }

    /**
     * 修改门店信息
     * @param storeBean
     * @return
     */
    @RequestMapping("/update")
    public ResponseMsg updateStore(StoreBean storeBean){

        int row = storeService.updateStore(storeBean);
        if (row>0){
            return new ResponseMsg().builder().code(200).msg("修改成功").build();
        }else {
            return new ResponseMsg().builder().code(201).msg("修改失败").build();
        }

    }

    /**
     * 根据id查询门店信息
     * @param storeId
     * @return
     */
    @RequestMapping("/findById")
    public ResponseMsg findById(Long storeId){

        StoreBean storeBean = storeService.findById(storeId);
        if (storeBean!=null){
            return new ResponseMsg().builder().code(200).data(storeBean).msg("查询成功").build();
        }else {
            return new ResponseMsg().builder().code(201).msg("查询失败").build();
        }
    }

    /**
     * 查询指定用户所有门店信息
     * @param userId
     * @return
     */
    @RequestMapping("/all")
    public ResponseMsg findAll(Long userId){

        List<StoreBean> storeBeans = storeService.findAll(userId);

        if (storeBeans!=null){
            return new ResponseMsg().builder().code(200).data(storeBeans).msg("查询成功").build();
        }else {
            return new ResponseMsg().builder().code(201).msg("查询失败").build();
        }
    }

    /**
     *导出当前用户的门店信息为excel
     * @return
     */
    @RequestMapping("/exportAll")
    public ResponseMsg exportAudit(long userId, HttpServletRequest request, HttpServletResponse response) throws Exception {

        //获取数据
        List<StoreBean> list = storeService.findAll(userId);
        // System.out.println(list);
        //excel标题
        String[] title = {"编码","门店名称","联系人","联系电话","地址","状态"};

        //excel文件名
        String fileName = "门店信息表"+System.currentTimeMillis()+".xls";

        //sheet名
        String sheetName = "门店信息表";
        String[][] content = new String[list.size()+1][title.length];
        for (int i = 0; i < list.size(); i++) {
            StoreBean obj = list.get(i);
            content[i][0] = obj.getStoreNum()+"";
            content[i][1] = obj.getStoreName();
            content[i][2] = obj.getPerson();
            content[i][3] = obj.getTelephone();
            content[i][4] = obj.getAddress();
            content[i][5] = obj.getStoreStatus()==1?"关闭":"开启 ";

        }

        //创建HSSFWorkbook
        HSSFWorkbook wb = ExcelUtil.getHSSFWorkbook(sheetName, title, content, null);

        //响应到客户端
        try {
            this.setResponseHeader(response,fileName);
            OutputStream os = response.getOutputStream();
            wb.write(os);
            os.flush();
            os.close();

        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 发送响应流方法
     * @param response
     * @param fileName
     */
    public void setResponseHeader(HttpServletResponse response, String fileName) {
        try {
            try {
                fileName = new String(fileName.getBytes(),"ISO8859-1");
            } catch (UnsupportedEncodingException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            response.setContentType("application/x-msdownload;charset=ISO8859-1");
            response.setHeader("Content-Disposition", "attachment;filename="+ fileName);
            response.addHeader("Pargam", "no-cache");
            response.addHeader("Cache-Control", "no-cache");
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }

}
